package com.qrxl.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qrxl.common.JGConstant;
import com.qrxl.common.JsonResult;
import com.qrxl.common.controller.BaseController;
import com.qrxl.common.vo.BaseQuery;
import com.qrxl.common.vo.PageVo;
import com.qrxl.common.vo.req.IdReq;
import com.qrxl.enums.EnumSysBoolean;
import com.qrxl.enums.EnumUserType;
import com.qrxl.user.entity.UserLogin;
import com.qrxl.user.entity.UserRole;
import com.qrxl.user.service.IRoleService;
import com.qrxl.user.service.IUserLoginService;
import com.qrxl.user.service.IUserRoleService;
import com.qrxl.user.vo.UserLoginInfo;
import com.qrxl.user.vo.req.*;
import com.qrxl.user.vo.res.UserExistRes;
import com.qrxl.user.vo.res.UserLoginListRes;
import com.qrxl.util.EnumUtil;
import com.qrxl.util.JGAssert;
import com.qrxl.util.QueryBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 登录表 前端控制器
 * </p>
 *
 * @author zhoukun
 * @since 2020-12-01
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("/user/userLogin")
public class UserLoginController extends BaseController {
    @Autowired
    IUserLoginService userLoginService;
    @Autowired
    IUserRoleService userRoleService;
    @Autowired
    IRoleService roleService;

    @PostMapping("/add")
    @ApiOperation(value = "用户新增")
    @ResponseBody
    public JsonResult add(@RequestBody @Validated UserAddReq req) {
        userLoginService.add(req, getUserLoginInfo());
        return JsonResult.genJsonResultByOk();
    }

    @GetMapping("/v1/queryList")
    @ApiOperation(value = "用户列表")
    @ResponseBody
    public JsonResult<PageVo<UserLoginListRes>> queryList(@Validated BaseQuery baseQuery, UserListReq req) {
        if(EnumUserType.USER.getCode().equals(getUserLoginInfo().getType())){
            return null;
        }
        QueryBuilder builder = new QueryBuilder<UserLogin>().vo2Entity(req, UserLogin.class).pageInfo(baseQuery)
                .ignoreFields("type","parentId")
                .addQuery((QueryWrapper queryWrapper) -> {
                    queryWrapper.ne("id", getUserLoginInfo().getId());
                    if (getUserLoginInfo().getType().equals(EnumUserType.ADMIN.getCode())) {
                        queryWrapper.eq("type", EnumUserType.USER.getCode());
                    }
                });
        PageVo<UserLoginListRes> pageVo = builder.buildPageVO(UserLoginListRes.class, userLoginService);
        pageVo.getRecords().forEach(i -> {
            if (StringUtils.isNotEmpty((i.getId()))) {
                i.setRoleList(roleService.selectListByUserId(i.getId()));
            }
        });

        return JsonResult.genJsonResultByOk(pageVo);
    }

    @ResponseBody
    @PostMapping("/v1/update")
    @ApiOperation(value = "用户编辑")
    public JsonResult update(@Validated @RequestBody UserUpdateReq req) {
        userLoginService.updateVo(req, getUserLoginInfo());
        return JsonResult.genJsonResultByOk();
    }

    @ResponseBody
    @PostMapping("/v1/login")
    @ApiOperation(value = "用户登录")
    public JsonResult login(@Validated @RequestBody UserLoginReq userLoginReq) {
        UserLoginInfo userLoginInfo = userLoginService.login(userLoginReq.getLoginName(), userLoginReq.getPassword());
        getSession().setAttribute(JGConstant.USER_SESSION_KEY, userLoginInfo);
        return JsonResult.genJsonResultByOk();
    }

    @ResponseBody
    @GetMapping("/v1/logout")
    @ApiOperation(value = "用户登出")
    public JsonResult login() {
        getSession().setAttribute(JGConstant.USER_SESSION_KEY, null);
        return JsonResult.genJsonResultByOk();
    }

    @ResponseBody
    @PostMapping("/v1/relRoles")
    @ApiOperation(value = "用户关联角色")
    public JsonResult relRoles(@RequestBody @Validated UserRelRoleReq req) {
        JGAssert.isTrue(!req.getUserId().equals(getUserLoginInfo().getId()), "不能给自己关联角色");
        userRoleService.relRoles(req);
        return JsonResult.genJsonResultByOk();
    }

    @ResponseBody
    @GetMapping("/v1/userRoleIdList")
    @ApiOperation(value = "用户ID获取关联的角色")
    public JsonResult userRoleIdList(@Validated IdReq req) {
        UserRole cond = new UserRole();
        cond.setUserId(req.getId());
        List<String> roleIdList = userRoleService.list(Wrappers.query(cond)).stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return JsonResult.genJsonResultByOk(roleIdList);
    }

    @ResponseBody
    @GetMapping("/v1/loginInfo")
    @ApiOperation(value = "用户获取当前登录的信息")
    public JsonResult<UserLoginInfo> userRoleIdList() {
        return JsonResult.genJsonResultByOk(getUserLoginInfo());
    }

    @ResponseBody
    @GetMapping("/v1/userExist")
    @ApiOperation(value = "用户登录名是否被占用")
    public JsonResult<UserExistRes> userExist(String loginName) {
        JGAssert.hasText(loginName, "loginName不能为空");
        EnumSysBoolean result = userLoginService.userExist(loginName);
        UserExistRes res = UserExistRes.builder()
                .exist(result.getCode())
                .existName(EnumUtil.findName(EnumSysBoolean.class, result.getCode()))
                .build();
        return JsonResult.genJsonResultByOk(res);
    }
}

